package Controller

import (
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"back_go/Response"
	"back_go/Util"
	"github.com/gin-gonic/gin"
	"log"
	"time"
)

// GetCategoryTable 查询菜单的表
/**
 * 获取菜单页面的表
 * @return
 */
func GetCategoryTable(c *gin.Context) {
	var db = gorm.Db
	var categoryList []GormModel.TzCategory
	//指定shop_id = 1
	db.Table("tz_category").Find(&categoryList).Where("shop_id = ?", "1")
	c.JSON(200, gin.H{
		"code":    "00000",
		"data":    categoryList,
		"msg":     "ok",
		"sign":    "",
		"success": true,
		"version": "v1.0",
	})
}

// GetCategoryList 查询菜单列表
func GetCategoryList(c *gin.Context) {
	var db = gorm.Db
	var categoryList []GormModel.TzCategory
	//SELECT category_id,shop_id,parent_id,category_name,icon,pic,seq,status,rec_time,grade,update_time FROM tz_category WHERE (grade <= 2 AND shop_id = 1) ORDER BY seq ASC
	db.Table("tz_category").Where("(grade <= ? AND shop_id = ?)", 2, "1").Order("seq ASC").Find(&categoryList)
	c.JSON(200, gin.H{
		"code":    "00000",
		"data":    categoryList,
		"msg":     "ok",
		"sign":    "",
		"success": true,
		"version": "v1.0",
	})
}

// GetCategoryById 查询菜单详情
/*
 * @param categoryId
 * @return GormModel.TzCategory
 */
func GetCategoryById(c *gin.Context) {
	var db = gorm.Db
	var category GormModel.TzCategory
	categoryId := c.Param("categoryId")
	db.Table("tz_category").Where("category_id =?", categoryId).Find(&category)
	c.JSON(200, gin.H{
		"code":    "00000",
		"data":    category,
		"msg":     "ok",
		"sign":    "",
		"success": true,
		"version": "v1.0",
	})

}

/*

/prod/category/listProdCategory 不知道有什么用，没写
*/

// DeleteCategoryById 删除分类
func DeleteCategoryById(c *gin.Context) {
	db := gorm.Db.Begin()
	categoryId := c.Param("categoryId")

	var err error
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			log.Printf(err.Error())
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()

	// 查询是否存在子分类
	var subCategoryCount int64
	err = db.Model(GormModel.TzCategory{}).Where("parent_id =?", categoryId).Count(&subCategoryCount).Error
	if subCategoryCount > 0 {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "该分类下有子分类，无法删除",
		})
		return
	}
	db.Delete(&GormModel.TzCategory{}, categoryId) //通过主键删除
	// 删除所有分类所关联的品牌 delete from tz_category_brand where category_id = #{categoryId}
	db.Delete(&GormModel.TzCategoryBrand{}, "category_id =?", categoryId)
	// 删除所有分类所关联的参数 	delete from tz_category_prop where category_id = #{categoryId}
	db.Delete(&GormModel.TzCategoryProp{}, "category_id =?", categoryId)

	c.JSON(200, Response.ResponseBody{
		Code:    "00000",
		Data:    nil,
		Success: true,
		Msg:     "删除成功",
	})
}

/*
GetListProdCategory
所有的产品分类
*/
func GetListProdCategory(c *gin.Context) {
	db := gorm.Db
	var list []GormModel.TzCategory
	db.Where("grade <=", 2).Find(&list)
	c.JSON(200, Response.ResponseBody{
		Code:    "00000",
		Msg:     nil,
		Data:    list,
		Success: true,
	})
}

func UpdateCategory(c *gin.Context) {
	var category GormModel.TzCategory
	var err error
	db := gorm.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			log.Printf(err.Error())
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()
	_ = c.BindJSON(&category)
	category.ShopID = 1 // 写死商店id
	if category.ParentID == category.CategoryID {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "分类的上级不能是自己本身",
		})
		return
	}
	var categoryName *GormModel.TzCategory
	err = db.Where("category_name = ? AND shop_id = ? AND category_id != ?", category.CategoryName, category.ShopID, category.CategoryID).First(&categoryName).Error
	if categoryName != nil && categoryName.CategoryID != 0 {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "分类名称已存在",
		})
		return
	}
	var categoryDb *GormModel.TzCategory
	err = db.First(&categoryDb, category.CategoryID).Error
	// 如果从下线改成正常，则需要判断上级的状态 先判断数据库有没有
	if categoryDb != nil && categoryDb.Status == 0 && category.Status == 1 && category.ParentID != 0 {
		var parentCategory *GormModel.TzCategory
		err = db.Where("category_id = ?", category.ParentID).First(&parentCategory).Error
		if parentCategory == nil || parentCategory.Status == 0 {
			// 修改失败，上级分类不存在或者不为正常状态
			c.JSON(200, Response.ResponseBody{
				Code:    "A00001",
				Data:    nil,
				Success: true,
				Msg:     "上级分类不存在或者不为正常状态",
			})
			return
		}
	}

	//开始更新
	now := time.Now()
	category.UpdateTime = &now
	category.RecTime = &now
	// 保存分类信息
	db.Save(&category)
	// 先删除后增加
	// 删除所有分类所关联的品牌 delete from tz_category_brand where category_id = #{categoryId}
	db.Delete(&GormModel.TzCategoryBrand{}, "category_id =?", category.CategoryID)
	// 删除所有分类所关联的参数 	delete from tz_category_prop where category_id = #{categoryId}
	db.Delete(&GormModel.TzCategoryProp{}, "category_id =?", category.CategoryID)
	//保存分类与品牌信息

	if Util.SliceIsNotEmpty(category.BrandIDs) {

		var categoryBrandList []GormModel.TzCategoryBrand
		for _, brandId := range category.BrandIDs {
			categoryBrandList = append(categoryBrandList, GormModel.TzCategoryBrand{
				CategoryID: category.CategoryID,
				BrandID:    brandId,
			})
		}
		batchSize := 100 // 每个批次插入 100 条记录
		err = db.CreateInBatches(categoryBrandList, batchSize).Error
	}
	//保存分类与参数信息
	if Util.SliceIsNotEmpty(category.AttributeIDs) {
		var categoryPropList []GormModel.TzCategoryProp
		for _, attributeId := range category.AttributeIDs {
			categoryPropList = append(categoryPropList, GormModel.TzCategoryProp{
				CategoryID: int64(category.CategoryID),
				PropID:     int64(attributeId),
			})
		}
		batchSize := 100 // 每个批次插入 100 条记录
		err = db.CreateInBatches(categoryPropList, batchSize).Error
	}

	c.JSON(200, Response.ResponseBody{
		Code:    "00000",
		Data:    nil,
		Success: true,
		Msg:     "修改成功",
	})
}
